import axios from 'axios';
import Qs from 'qs'
import './httpInterceptors';
/*
 * 执行http请求
 * 自动转化配置文件config中的参数转化为url参数
 * @param {Object} options axios.request的参数
 * @returns Promise.
 */

class Http {
  static request(options) {
    if(options.method.toUpperCase() === 'POST') {
      window.document.getElementById('api_loding_id').style.display='block';
    }
    return new Promise(function (resolve, reject) {
      const config = {
        headers: {'X-Requested-With': 'XMLHttpRequest','Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
        url: options.url,
        method: options.method,
        //withCredentials: true
      };
      if(options.method.toUpperCase() === 'GET') {
        config.params = options.data;
      } else if(options.method.toUpperCase() === 'POST') {
        config.data = options.data;
      }
      //将payload数据传输形式转成formdata
      if(typeof options.upload == 'undefined') {
        config.transformRequest = [function (data) {
          return data = Qs.stringify(data);
        }];
      }else{
        if(typeof options.onUploadProgress != 'undefined') {
          config.onUploadProgress = options.onUploadProgress;
        }
      }
      axios.request(config).then((res)=>{
        window.document.getElementById('api_loding_id').style.display='none';
        if(res.status != 200) {
          alert(options.url+'接口异常，错误码'+res.status);
        } else {
          if(res.data.errorCode == '101') {
            if(options.data && options.data.noshowLoginDailog) {
              resolve(res.data);
            }else {
              window.document.getElementById('login_timeout_id').style.display='block';
              return;
            }
          }else {
            resolve(res.data);
          }
        }
      }).catch((error)=>{
        window.document.getElementById('api_loding_id').style.display='none';
        if(options.url.indexOf('getJssdk') == -1 && options.url.indexOf('getOrderTicketStatus') == -1) {
          if(error.message && error.message.indexOf('Network Error') != -1) {
            // alert('您的网络异常，请检查您手机的网络情况！'+options.url);
          } else if(error.message && error.message.indexOf('timeout of') != -1) {
            // alert('接口URL'+options.url+'超时');
          } else if(error.message){
            alert(error.message);
          }
        }
      });
    });
  }
}
export default Http;
